﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using System.IO;

namespace TimeWar.ContentProcessor.Terrain
{

    // all processors must derive from this class
    [ContentProcessor]
    public class TerrainProcessor : ContentProcessor<TerrainContent,
    TerrainContent>
    {
        public override TerrainContent Process(TerrainContent input,
        ContentProcessorContext context)
        {
            return new TerrainContent(input.height);
        }
    }

    // stores information about importer, file extension, and caching
    [ContentImporter(".raw", DefaultProcessor = "TerrainProcessor")]

    // ContentImporter reads original data from original media file
    public class TerrainPipeline : ContentImporter<TerrainContent>
    {
        // reads original data from binary or text based files
        public override TerrainContent Import(String filename,
                                              ContentImporterContext context)
        {
            byte[] bytes = File.ReadAllBytes(filename);
            TerrainContent terrain = new TerrainContent(bytes);
            return terrain; // returns compiled data object
        }
    }

    // write compiled data to *.xnb file
    [ContentTypeWriter]
    public class TerrainWriter : ContentTypeWriter<TerrainContent>
    {
        protected override void Write(ContentWriter cw,
                                      TerrainContent terrain)
        {
            cw.Write(terrain.NUM_ROWS);
            cw.Write(terrain.NUM_COLS);
            cw.Write(terrain.worldWidth);
            cw.Write(terrain.worldHeight);
            cw.Write(terrain.heightScale);
            cw.Write(terrain.cellWidth);
            cw.Write(terrain.cellHeight);

            for (int row = 0; row < terrain.NUM_ROWS; row++)
            {
                for (int col = 0; col < terrain.NUM_COLS; col++)
                {
                    cw.Write(terrain.position[col + row * terrain.NUM_COLS]);
                    cw.Write(terrain.normal[col + row * terrain.NUM_COLS]);
                }
            }
        }

        // Sets the CLR data type to be loaded at runtime.
        public override string GetRuntimeType(TargetPlatform targetPlatform)
        {
            //return "TimeWar.Shared.Config.TerrainConfig, TimeWarShared, Version=0.0.0.0-99.9.9.9, Culture=neutral";
            return "TimeWar.Shared.Config.TerrainConfig, TimeWarShared";
        }
        // Tells the content pipeline about reader used to load .xnb data
        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return "TimeWar.Shared.Config.TerrainReader, TimeWarShared";
        }
    }


}
